<?php
/**
 * 
 * App for changing user preferences/setting
 * 
 * @category Abovo
 * 
 * @package Abovo_App_System
 * 
 * @subpackage Abovo_App_System_Prefs
 * 
 * @author Antti Holvikari <anttih@gmail.com>
 * 
 * @license http://opensource.org/licenses/gpl-license.php GPL
 *
 */

/**
 * 
 * App for changing user preferences/setting
 * 
 * @category Abovo
 * 
 * @package Abovo_App_System
 * 
 * @subpackage Abovo_App_System_Prefs
 * 
 */
class Abovo_App_System_Prefs extends Abovo_App_System {
    
    /**
     * Default action
     *
     * @var string
     */
    protected $_action_default = 'settings';
    
    /**
     * Contact form
     *
     * @var Solar_Form
     */
    public $user_form;
    
    /**
     * Password form
     *
     * @var Solar_Form
     */
    public $password_form;
    
    /**
     * 
     * Change settings
     * 
     * @return void
     * 
     */
    public function actionSettings()
    {
        // fix WebKit bug when uploading a file
        $this->_response->setHeader('connection', 'close');
        
        // change password
        $this->_actionPassword();
        
        // change contact info
        $this->_actionContactInfo();
    }
    
    /**
     * 
     * Change users contact information
     * 
     * @return void
     * 
     */
    protected function _actionContactInfo()
    {
        $handle = Solar::registry('user')->auth->handle;
        
        // fetch contact form
        $users = Solar::factory('Abovo_Model_Contacts_Users');
        $form  = $users->form();
        
        // fetch contact info
        $user = $users->fetchByHandle($handle);
        
        $form->setElement('picture', array(
            'type'  => 'file',
            'label' => $this->locale('LABEL_PICTURE'),
        ));
        
        $form->setElement('process', array(
            'type'  => 'submit',
            'value' => $this->locale('PROCESS_EDIT'),
        ));
        
        if ($this->_isProcess('edit')) {
            if ($form->validate()) {
                $values = $form->values();
                $values['contact']['id'] = $user->id;
                
                // save contact
                $users->save($values['contact']);
                
                $this->_processPicture($form);
            }
        } else {
            // populate form with contact info because nothing was
            // submitted
            $form->populate(array('contact' => $user->toArray()));
        }
        
        // assign form for view
        $this->user_form = $form;
    }
    
    /**
     * Action to change password
     *
     * @return void
     */
    protected function _actionPassword()
    {
        $auth = Solar::registry('auth');
        
        // New form object
        $form = Solar::factory('Abovo_Form');
        
        // Elements
        $elements = array(
            'passwd' => array(
                'type'  => 'password',
                'label' => $this->locale('LABEL_PASSWD'),
            ),
            'new_passwd' => array(
                'type'   => 'password',
                'label'  => $this->locale('LABEL_PASSWD_NEW'),
                'filter' => array(array(
                    'validateRegex',
                    sprintf($this->locale('VALID_REGEX'), 5, 20),
                    '/[a-z0-9]{5,15}$/',
                )),
            ),
            'new_passwd2' => array(
                'type' => 'password',
                'label' => $this->locale('LABEL_PASSWD_CONFIRM'),
            ),
            'process' => array(
                'type' => 'submit',
                'value' => $this->locale('PROCESS_SAVE'),
            ),
        );
        
        // Set password form elements
        $form->setElements($elements);

        // Are we going to do this?
        if ($this->_isProcess('save')) {
            // Fetch values and populate the form
            $form->populate();
            // Get submit values
            $values = $form->values();
            // user handle
            $handle = Solar::registry('user')->auth->handle;
            
            // Does user match password?
            if ($auth->isValidPassword($handle, $values['passwd'])) {
                // Does the form validate?
                if ($form->validate()) {
                    // Do passwords match?
                    if ($values['new_passwd'] === $values['new_passwd2']) {
                        // Yes, change password
                        $auth->update(array(
                            'password' => hash('md5', $values['new_passwd'])), 
                            array('handle = ?' => $handle)
                        );
                        
                    } else {
                        $form->setStatus(false);
                        $form->feedback = array($this->locale('FAILURE_FORM'));
                        $form->addFeedback(array(
                            'new_passwd2' => $this->locale('VALID_PASSWD_NO_MATCH')
                        ));                       
                    }
                }
            } else {
                $form->setStatus(false);
                $form->feedback = array($this->locale('FAILURE_FORM'));
                $form->addFeedback(array(
                    'passwd' => Solar::$locale->fetch('Solar_Auth_Adapter', 'WRONG')
                ));
            }
        }
        
        // Assign form for view
        $this->password_form = $form;
    }
    
    /**
     * 
     * Process the file upload
     * 
     * Creates a small avatar image
     * 
     * @return void
     * 
     */
    private function _processPicture($form)
    {
        // new upload processor
        $upload = Solar::factory(
            'Lux_Filesystem_Upload',
            array(
                'extensions'  => array('jpg' => 'image/jpeg'),
                'max_size'    => 400960,
            )
        );
        
        try {
            // set upload file
            $upload->init($this->_request->files['picture']);
            
            // get upload file info
            $file = $upload->getTmpFileInfo();
            
            // create small image
            Solar::factory('Abovo_Image_Avatar')->createSmall(
                $file['tmp_name'],
                $this->user->handle
            );
            
        } catch (Lux_Filesystem_Upload_Exception $e) {
            // there was an error somewhere, set form element feedback
            $form->elements['picture']['feedback'][] = $e->getMessage();
        }
    }
}
